using UnityEngine;
using System;
using System.Collections;
using System.IO.Ports;
using System.Threading;

public enum Movement {
	LEFT,
	RIGHT,
	NONE
}

public class Controllers : MonoBehaviour {
	public SerialPort sp;
	public int[] pos;
	public bool button;
	public Movement movement;
	private Thread worker;

	void Worker() {
		bool good = false;
		int fcount = 0;
		pos = new int[8];
		for (int i = 0; i < 8; i++) {
			pos[i] = 0;
		}
		button = false;
		movement = Movement.NONE;
		
		while (true) {
			try {
				Thread.Sleep(1);
				char c = (char)sp.ReadChar();
				if (c == 'F') {
					good = false;
					fcount++;
					if (fcount == 8) {
						fcount = 0;
						good = true;
					}
				}
				if (good) {
					for (int i = 0; i < 8; i++) {
						Thread.Sleep(1);
						pos[i] = Convert.ToInt32(((char)sp.ReadChar()).ToString());
					}
					if (((char)sp.ReadChar()).ToString() == "1") {
						button = true;
					} else {
						button = false;
					}
					string m = ((char)sp.ReadChar()).ToString();
					if (m == "+") {
						movement = Movement.RIGHT;
					} else if (m == "-") {
						movement = Movement.LEFT;
					} else {
						movement = Movement.NONE;
					}
					good = false;
				}
			} catch (Exception) {}
		}
	}
	
	void Start () {
		sp = new SerialPort("COM5", 9600, Parity.None, 8, StopBits.One);
		sp.Open();
        sp.ReadTimeout = 5000;
		worker = new Thread(new ThreadStart(this.Worker));
		worker.Start();
	}
	
	void End() {	
		worker.Abort();
        sp.Close();
	}
	
	void Update () {
		string output = "";
		for (int i = 0; i < 8; i++) {
			output += i + ":" + pos[i] + "  ";
		}
		output += (button ? "T" : "F") + " " + (movement == Movement.LEFT ? "L" : (movement == Movement.RIGHT ? "R" : "-"));
		print(output);
	}
}
